/*
 * author      : dormi330
 * date        : 2018/6/29
 * project     : mybatis
 * description : 购物车-command-服务
 */

package com.deep.trade.application.cart;

import com.deep.trade.common.CommonUtils;
import com.deep.trade.common.TradeException;
import com.deep.trade.adaptor.required.member.Member;
import com.deep.trade.adaptor.required.member.MemberService;
import com.deep.trade.adaptor.required.sku.ItemSkuService;
import com.deep.trade.adaptor.required.sku.Sku;
import com.deep.trade.cart.dto.InDtoCart;
import com.deep.trade.cart.dto.InDtoCartDelete;
import com.deep.trade.domain.cart.CommandOfCart;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CartService {
    private Logger logger = LoggerFactory.getLogger(this.getClass().getName());
    private MemberService memberService;
    private ItemSkuService itemSkuService;
    private CommandOfCart commandOfCart;

    @Autowired
    public CartService(MemberService memberService, ItemSkuService itemSkuService, CommandOfCart commandOfCart) {
        this.memberService = memberService;
        this.itemSkuService = itemSkuService;
        this.commandOfCart = commandOfCart;
    }

    public void addSkuToCart(InDtoCart inDtoCart) throws Exception {
        logger.info("{}, inDtoCart={}", CommonUtils.currentClassAndMethod(), inDtoCart.toString());

        Member member = memberService.assureMemberOfToken();
        if (null == inDtoCart.getSkuId()) throw new TradeException("skuId cannot be null");

        Sku sku = itemSkuService.skuOfId(inDtoCart.getSkuId());
        if (null == sku) throw new TradeException("sku cannot be found!");

        commandOfCart.addSkuToCart(member.getId(), sku, inDtoCart.getQuantity());
    }

    public void removeSkuFromCart(InDtoCartDelete inDtoCartDelete) throws Exception {
        logger.info("{}, inDtoCart={}", CommonUtils.currentClassAndMethod(), inDtoCartDelete.toString());
        Member member = memberService.memberOfToken();
        List<String> skuIdList = inDtoCartDelete.getSkuIdList();

        commandOfCart.removeSkuFromCart(member.getId(), skuIdList);
    }

    public void alterQuantity(InDtoCart inDtoCart) throws Exception {
        logger.info("{}, inDtoCart={}", CommonUtils.currentClassAndMethod(), inDtoCart.toString());
        Member member = memberService.memberOfToken();
        String skuId = inDtoCart.getSkuId();
        int qty = inDtoCart.getQuantity();

        commandOfCart.alterQuantity(member.getId(), skuId, qty);
    }
}
